/**
 * Created by user on 2016/1/5.
 */

angular.module('mis.splashScreenManager.controllers', [])
    .controller('splashScreenCtrl', ['$scope', '$http', '$filter', function ($scope, $http, $filter) {
        $scope.currentPage = 1;
        $scope.pageSize = 15;
        $scope.splash_ = {};
        $scope.splash_query = {}
        $scope.splash_.duration = 2;


        //分页
        $scope.pagination = new pagination({
            currentPage: $scope.currentPage, pageSize: $scope.pageSize,
            url: 'http://' + backOfficeHost + '/rest/v1.0/mis/master/splashScreenList/:page/:size',
            ajax: $http,
            success: function (data) {
                $('#loading').modal("close");
                data.data.list.forEach(function (temp) {
                    temp.image = 'http://' + imgHost + temp.image;
                    console.log(temp.image)
                    temp.startDate = new Date(temp.startDate).format('yyyy-MM-dd hh:mm');
                    temp.endDate = new Date(temp.endDate).format('yyyy-MM-dd hh:mm');
                });
                $scope.splashList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;


                $scope.currentPage = $(".am-active").text();
                $scope.pagination.totalPage = data.data.totalPage;
                $scope.pagination.pageHeader($scope.pageNumber);
                $('#count').text("共" + $scope.pageNumber + "页 有" + $scope.count + "数据");
            },
            error: function (err) {
                $scope.splashList = null;
                $('#loading').modal("close");
            },
            params: {}
        });


        //$scope.splashEdit = {};
        $scope.selectFile = function (files, model) {
            if (model == 'add') {
                document.getElementById("image_result").innerHTML = '';
            } else {
                document.getElementById("image_result_edit").innerHTML = '';
            }
            showImages(model);
        };

        var reader = null;
        if (FileReader) {
            reader = new FileReader();
        } else {
            alert("浏览器暂时不支持FileReader");
        }
        var fileList = {}, length = 0, length1 = 0;
        var showImages = function (model) {

            if (model == 'add') {
                var imageEle = document.getElementById("images_upload");
            } else {
                var imageEle = document.getElementById("images_upload_edit");
            }

            //获取上传的多个文件
            fileList = imageEle.files;
            length = fileList.length;
            length1 = fileList.length;

            //获取文件信息
            readURL(model);
        };

        var readURL = function (model) {

            reader.readAsDataURL(fileList[length1 - length]);
            reader.onload = function () {
                var img = document.createElement("img");
                img.src = reader.result;
                img.width = 48;
                img.height = 78;
                if (model == 'add') {
                    document.getElementById("image_result").appendChild(img);
                } else {
                    document.getElementById("image_result_edit").appendChild(img);
                }
                length--
                if (length == 0)return;
                readURL(model);
            };
        };

        $scope.initSplashAdd = function () {
            $scope.splash_.duration = 2;
            //http://localhost:3008/rest/v1.0/mis/master/splashScreenLatestStartDate
            $http.get('http://' + backOfficeHost + '/rest/v1.0/mis/master/splashScreenLatestStartDate', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.data)
                    $scope.splash_.startDate = new Date(data.data).format('yyyy-MM-dd hh:mm');
            }).error(function () {

            });
        };


        $scope.addSplashScreen = function (splash) {
            $scope.clickType = "add";
            $scope.splash = {};

            splash.startDate = $('#start_date').val();
            splash.endDate = $('#end_date').val()

            if ( splash.startDate &&  splash.endDate) {

                if (splash.startDate > splash.endDate)
                {
                    alert('开始日期不能大于结束日期');
                    console.log('开始日期不能大于结束日期');
                    return;
                }
            } else {
                alert('结束日期不能空');
                return;
            }

            var fd = new FormData();
            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    var index = i + 1;
                    fd.append('image' + index, fileList[i]);
                    console.log('image' + index + " --" + fileList[i]);
                }
            }
            console.log("splash", splash);

            if (splash.startDate)  fd.append('startDate', splash.startDate);
            if (splash.endDate)    fd.append('endDate', splash.endDate);
            if (splash.duration)   fd.append('duration', splash.duration);
            if (splash.desc)       fd.append('desc', splash.desc);
            if (splash.objId)      fd.append('_id', splash.objId);
            console.log('splash.objId' + splash.objId);
            $('#loading').modal({target: '#loading'});
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/master/splashScreenAdd', fd, {
                timeout: 9000,
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function (data) {
                $('#loading').modal("close");
                if (data.result.status == 1) {
                    $('#doc-modal-splash').modal("close");
                    alert("添加成功");
                    $scope.searchSplashScreen();
                } else {
                    alert("开始结束日期可能存在重叠");
                }
                //$('#loading').modal("close");
                //alert("添加成功'");
                //$scope.searchSplashScreen();
            }).error(function () {

                $('#loading').modal("close");
                alert("添加失败");
            });
        };

        $scope.delSplashScreen = function (_id, index) {
            $('#loading').modal({target: '#loading'});

            $http.get('http://' + backOfficeHost + '/rest/v1.0/mis/master/splashScreenDel/' + _id, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $('#loading').modal("close");
                alert("删除成功'");
                //$scope.splashList.splice(index, 1);
                $scope.searchSplashScreen(true);
            }).error(function () {
                console.log(data)
                $('#loading').modal("close");
                alert("删除失败");
            });
        };

        $scope.editSplashScreen = function (splash) {

            $scope.splashEdit.startDate = $('#start_date_edit').val();
            $scope.splashEdit.endDate = $('#end_date_edit').val();

            if ( $scope.splashEdit.endDate && $scope.splashEdit.startDate)  {
                if ($scope.splashEdit.startDate > $scope.splashEdit.endDate)
                {
                    alert('开始日期不能大于结束日期');
                    console.log('开始日期不能大于结束日期');
                    return;
                }
            } else {
                alert('日期为空');
                return;
            }

            var fd = new FormData();
            $scope.clickType = "edit";

            var _id = $scope.splashEdit.objId;
            fd.append('objId', _id);
            console.log('objId ' + _id);
            $scope.splashEdit = splash;

            console.log($scope.splashEdit);


            if (fileList != null) {
                for (var i = 0; i < fileList.length; i++) {
                    var index = i + 1;
                    fd.append('image' + index, fileList[i]);
                    console.log(fileList[i]);
                }
            }
            console.log($scope.splashEdit);
            if ($scope.splashEdit.startDate)  fd.append('startDate', $scope.splashEdit.startDate);
            if ($scope.splashEdit.endDate)    fd.append('endDate', $scope.splashEdit.endDate);
            if ($scope.splashEdit.duration)   fd.append('duration', $scope.splashEdit.duration);
            if ($scope.splashEdit.desc)       fd.append('desc', $scope.splashEdit.desc);
            $('#loading').modal({target: '#loading'});


            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/master/splashScreenEdit', fd, {
                transformRequest: angular.identity, headers: {'Content-Type': undefined}
            }).success(function (data) {
                $('#loading').modal("close");
                console.log(data)
                //{"result":{"status":0,"message":"Exception happen when splashScreen..."},"data":null}
                if (data.result.status == 1) {
                    $('#doc-modal-edit').modal("close");
                    alert("更新成功");
                    $scope.searchSplashScreen($scope.pagination.currentPage);
                } else {
                    if (data.result.message) {
                        alert("开始结束日期存在重叠");
                    }
                }
            }).error(function () {
                $('#loading').modal("close");
                alert("更新失败");
            });
        };

        $scope.editSplash = function (splash) {
            $scope.splashEdit = splash;
            console.log("更新点击，有objId 否" + $scope.splashEdit);
            console.log(splash);
            console.log($scope.splashEdit);
            document.getElementById("image_result_edit").innerHTML = "";
            var img = document.createElement("img");
            img.src = $scope.splashEdit.image;
            img.width = 48;
            img.height = 78;
            document.getElementById("image_result_edit").appendChild(img)
        }

        $scope.eqeqeq = function (str) {
            if (str === $scope.clickType) {
                return true
            } else {
                return false;
            }
        }


        $scope.searchSplashScreen = function (current) {

            if (current) {
                $scope.currentPage = $scope.pagination.currentPage;
            } else {
                $scope.pagination.currentPage = 1;
                $scope.currentPage = 1;
            }

            console.log($scope.splash_query);
            $('#loading').modal({target: '#loading'});
            $http.post('http://' + backOfficeHost + '/rest/v1.0/mis/master/splashScreenList/' + $scope.currentPage + '/' + $scope.pageSize, $scope.splash_query, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                data.data.list.forEach(function (temp) {
                    temp.image = 'http://' + imgHost + temp.image;
                    console.log(temp.image)
                    temp.startDate = new Date(temp.startDate).format('yyyy-MM-dd hh:mm');
                    temp.endDate = new Date(temp.endDate).format('yyyy-MM-dd hh:mm');
                });
                $scope.splashList = data.data.list;
                $scope.pageNumber = data.data.totalPage;
                $scope.count = data.data.count;
                $('#count').text("共" + $scope.pageNumber + "页 有" + $scope.count + "数据");

                $('#loading').modal('close');
            }).error(function () {
                $('#loading').modal("close");
            });
        };

    }]);
